﻿
using System;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using Labthink.PCSoft.UniversalHost4.UserControls.MsgBox;
using Labthink.PCSoft.UniversalHost4.Utility;
using Microsoft.Reporting.WinForms;
using Report.Forms;

namespace Report
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class FrmMultiavityReport1
    {
        // ReSharper disable once InconsistentNaming
        private static readonly string localPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        public bool CanSave { get; set; } = true;
        public MultiavityReportManager1 Manager { get; set; }
        private int _defaultZoom = 100;
        private int _maxPage;

        public FrmMultiavityReport1()
        {
            InitializeComponent();
            Resources.MergedDictionaries.Add(ReportCommon.GetLan);
        }

        public static string LocalPath => localPath;

        private void FrmReport_OnLoaded(object sender, RoutedEventArgs e)
        {
            if (!CanSave)
            {
                BtnSaveConfig.Visibility = Visibility.Collapsed;
            }
            Top = 0;
            Left = 0;
            Height = SystemParameters.FullPrimaryScreenHeight + 35;
            Width = SystemParameters.FullPrimaryScreenWidth;
            _initPermessions();
            if (Manager.AddInputs.Count > 0)
            {
                var frm = new FrmInputValues2();
                frm.ShowDialog(this);
            }
            _loadReport();
        }

        private void _loadReport()
        {
            var ds = Manager.CreateReportData();
            var s = Manager.CreateReportStream(localPath + "/Report/MultiavityReport1.rdlc");
            ReportViewer.LocalReport.LoadReportDefinition(s);
            //ReportViewer.LocalReport.ReportPath = localPath + "/Report/Report1.rdlc";
            ReportViewer.Messages = new ReportLanguage();
            ReportViewer.LocalReport.EnableExternalImages = true;
            ReportViewer.LocalReport.DataSources.Clear();

            foreach (DataTable dt in ds.Tables)
            {
                ReportViewer.LocalReport.DataSources.Add(new ReportDataSource(dt.TableName, dt));
            }

            ReportViewer.RefreshReport();
            ReportViewer.ZoomMode = ZoomMode.PageWidth;
            _maxPage = ReportViewer.GetTotalPages();
            //TxtPageAll.Text = _maxPage + "";
            Task.Run(() =>
            {
                Thread.Sleep(1000);
                _maxPage = -1;
                for (int i = 0; i < 5; i++)
                {
                    _maxPage = ReportViewer.GetTotalPages();
                    Thread.Sleep(1000);
                }
                //_maxPage = t;

                Dispatcher?.Invoke(() => TxtPageAll.Text = _maxPage + "");
            });
        }

        private void AddParam_OnClick(object sender, RoutedEventArgs e)
        {
            var frm = new FrmAdd();
            var r = frm.ShowDialog(this);
            if (r.HasValue && r.Value)
            {
                Manager.AddParam(frm.StrName, frm.Value);
                _loadReport();
            }
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            var r = Manager.SaveConfigAsync();
            string message;
            if (r > 0)
            {
                message = LanguageManager.GetLanguageValue("ActionSuccess");
            }
            else
            {
                message = LanguageManager.GetLanguageValue("ActionFail");
            }

            MyMessageBox.Show(this,message);
        }

        private void RemoveParam_OnClick(object sender, RoutedEventArgs e)
        {
            var frm = new FrmRemove { Datas = Manager.ParamInfo, Selecteds = Manager.ParamSelected };
            var r = frm.ShowDialog(this);
            if (r.HasValue && r.Value)
            {

                Manager.RemoveParams(frm.Removes);
                _loadReport();
            }
        }

        private void ParamSequence_OnClick(object sender, RoutedEventArgs e)
        {
            var frm = new FrmSequence { Datas = Manager.ParamInfo, Selecteds = Manager.ParamSelected };
            var r = frm.ShowDialog(this);
            if (r.HasValue && r.Value)
            {
                Manager.SequenceParams(frm.Seqs);
                //Manager.RemoveParams(frm.Removes);
                _loadReport();
            }
        }

        private void AddCurve_OnClick(object sender, RoutedEventArgs e)
        {
            var frm = new FrmAddResultCurve();
            var r = frm.ShowDialog(this);
            if (r.HasValue && r.Value)
            {
                _loadReport();
            }
        }

        private void RemoveCurve_OnClick(object sender, RoutedEventArgs e)
        {
            var frm = new FrmRemoveResultCurve();
            var r = frm.ShowDialog(this);
            if (r.HasValue && r.Value)
            {
                _loadReport();
            }
        }

        private void ReportViewer_OnPrint(object sender, ReportPrintEventArgs e)
        {
            //MessageBox.Show("打印");
            Manager.Log(string.Format(ReportCommon.GetLan.GetLanguageValue("ReportLogPrint"), Manager.Id));
        }

        private void ReportViewer_OnReportExport(object sender, ReportExportEventArgs e)
        {
            //MessageBox.Show(e.Extension.Name);
            Manager.Log(string.Format(ReportCommon.GetLan.GetLanguageValue("ReportLog" + e.Extension.Name), Manager.Id));
        }

        private void ReportViewer_OnRenderingBegin(object sender, CancelEventArgs e)
        {
            //foreach (RenderingExtension extension in ReportViewer.LocalReport.ListRenderingExtensions())
            //{
            //    if (extension.Name == "PDF" && Manager.Permissions.All(p => p.Code != "﻿ExportPDF".Clear()))
            //    {
            //        //extension.Visible = false; // Property is readonly...
            //        FieldInfo fi = extension.GetType().GetField("m_isVisible", BindingFlags.Instance | BindingFlags.NonPublic);
            //        if (fi != null) fi.SetValue(extension, false);
            //    }
            //    if (extension.Name == "WORDOPENXML" && Manager.Permissions.All(p => p.Code != "﻿ExportWord".Clear()))
            //    {
            //        //extension.Visible = false; // Property is readonly...
            //        FieldInfo fi = extension.GetType().GetField("m_isVisible", BindingFlags.Instance | BindingFlags.NonPublic);
            //        if (fi != null) fi.SetValue(extension, false);
            //    }
            //    if (extension.Name == "EXCELOPENXML" && Manager.Permissions.All(p => p.Code != "﻿ExportExcel".Clear()))
            //    {
            //        //extension.Visible = false; // Property is readonly...
            //        FieldInfo fi = extension.GetType().GetField("m_isVisible", BindingFlags.Instance | BindingFlags.NonPublic);
            //        if (fi != null) fi.SetValue(extension, false);
            //    }
            //}
        }

        private void _initPermessions()
        {
            if (Manager.Permissions.All(p => p.Code != "﻿PrintReport".Clear())) BtnPrint.Visibility = Visibility.Collapsed;
            if (Manager.Permissions.All(p => p.Code != "﻿ExportPDF".Clear())) BtnPdf.Visibility = Visibility.Collapsed;
            if (Manager.Permissions.All(p => p.Code != "﻿ExportWord".Clear())) BtnWord.Visibility = Visibility.Collapsed;
            if (Manager.Permissions.All(p => p.Code != "﻿ExportExcel".Clear())) BtnExcel.Visibility = Visibility.Collapsed;
            if (Manager.Permissions.All(p => p.Code != "﻿AddParam".Clear())) TxtAddParam.Visibility = Visibility.Collapsed;
            if (Manager.Permissions.All(p => p.Code != "﻿RemoveParam".Clear())) TxtRemoveParam.Visibility = Visibility.Collapsed;
            if (Manager.Permissions.All(p => p.Code != "﻿ModiflyResultList".Clear())) TxtResultList.Visibility = Visibility.Collapsed;
            //if (Manager.Permissions.All(p => p.Code != "﻿ModiflyCurve".Clear())) AddCurve.Visibility = Visibility.Collapsed;
            if (Manager.Permissions.All(p => p.Code != "﻿AddCurve".Clear())) TxtAddCurve.Visibility = Visibility.Collapsed;
            if (Manager.Permissions.All(p => p.Code != "﻿RemoveCurve".Clear())) TxtRemoveCurve.Visibility = Visibility.Collapsed;
            if (Manager.Permissions.All(p => p.Code != "﻿SaveReportConfig".Clear())) BtnSaveConfig.Visibility = Visibility.Collapsed;


        }

        private void ModiflyResultList_OnClick(object sender, RoutedEventArgs e)
        {
            var frm = new FrmResultList1();
            var r = frm.ShowDialog(this);
            if (r.HasValue && r.Value)
            {
                _loadReport();
            }
        }

        private void ResultPrecision_OnClick(object sender, RoutedEventArgs e)
        {
            var frm = new FrmPrecision { Datas = Manager.ResultInfo, Selecteds = Manager.ResultSelected };
            var r = frm.ShowDialog(this);
            if (r.HasValue && r.Value)
            {
                Manager.PrecisionResults(frm.Seqs);
                //Manager.RemoveParams(frm.Removes);
                _loadReport();
            }
        }


        private void ButtonClose_OnClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void UIElement_OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            BtnMenuhide_OnClick(null, null);
        }

        private void BtnMenuhide_OnClick(object sender, RoutedEventArgs e)
        {
            BtnMenuShow.Visibility = Visibility.Visible;
            BtnMenuhide.Visibility = Visibility.Collapsed;
            ColMenu.Width = new GridLength(0);
        }

        private void BtnMenuShow_OnClick(object sender, RoutedEventArgs e)
        {
            BtnMenuShow.Visibility = Visibility.Collapsed;
            BtnMenuhide.Visibility = Visibility.Visible;
            ColMenu.Width = new GridLength(280);
        }

        #region 报告菜单
        private void BtnFirst_OnClick(object sender, RoutedEventArgs e)
        {
            ReportViewer.CurrentPage = 1;
            TxtPage.Text = ReportViewer.CurrentPage + "";
        }

        private void BtnPrevous_OnClick(object sender, RoutedEventArgs e)
        {
            if (ReportViewer.CurrentPage != 1)
                ReportViewer.CurrentPage--;
            TxtPage.Text = ReportViewer.CurrentPage + "";
        }

        private void BtnNext_OnClick(object sender, RoutedEventArgs e)
        {
            if (ReportViewer.CurrentPage < _maxPage)
                ReportViewer.CurrentPage++;
            TxtPage.Text = ReportViewer.CurrentPage + "";
        }

        private void BtnLast_OnClick(object sender, RoutedEventArgs e)
        {
            ReportViewer.CurrentPage = ReportViewer.LocalReport.GetTotalPages();
            TxtPage.Text = ReportViewer.CurrentPage + "";
        }


        private void BtnReset_OnClick(object sender, RoutedEventArgs e)
        {
            ReportViewer.Reset();
            TxtPageAll.Text = ReportViewer.LocalReport.GetTotalPages() + "";
        }

        private void BtnRefresh_OnClick(object sender, RoutedEventArgs e)
        {
            ReportViewer.RefreshReport();
        }

        private void BtnPrint_OnClick(object sender, RoutedEventArgs e)
        {
            ReportViewer.PrintDialog();
        }

        private void BtnView_OnClick(object sender, RoutedEventArgs e)
        {
            if (ReportViewer.DisplayMode == DisplayMode.Normal)
                ReportViewer.SetDisplayMode(DisplayMode.PrintLayout);
            else ReportViewer.SetDisplayMode(DisplayMode.Normal);
            ReportViewer.ZoomMode = ZoomMode.PageWidth;
            //
            //TxtPageAll.Text = ReportViewer.GetTotalPages() + "";
            Task.Run(() =>
            {
                Thread.Sleep(1000);
                _maxPage = -1;
                for (int i = 0; i < 5; i++)
                {
                    _maxPage = ReportViewer.GetTotalPages();
                    Thread.Sleep(1000);
                }

                //_maxPage = t;
                Dispatcher?.Invoke(() => TxtPageAll.Text = _maxPage + "");
            });
        }

        private void BtnSetting_OnClick(object sender, RoutedEventArgs e)
        {
            ReportViewer.PageSetupDialog();
        }

        private void BtnWord_OnClick(object sender, RoutedEventArgs e)
        {
            ReportViewer.Invoke(new ExportTo(ExportToFile), "Word");
        }

        private void BtnExcel_OnClick(object sender, RoutedEventArgs e)
        {
            ReportViewer.Invoke(new ExportTo(ExportToFile), "Excel");
        }

        private void BtnPdf_OnClick(object sender, RoutedEventArgs e)
        {
            ReportViewer.Invoke(new ExportTo(ExportToFile), "Pdf");
        }

        private void TxtPage_OnTextChanged(object sender, TextChangedEventArgs e)
        {
            if (ReportViewer == null) return;
            int p;
            if (int.TryParse(TxtPage.Text, out p))
            {
                if (p <= ReportViewer.LocalReport.GetTotalPages() && p >= 1)
                    ReportViewer.CurrentPage = p;
            }
        }

        private void BtnZoomIn_OnClick(object sender, RoutedEventArgs e)
        {
            _defaultZoom += 25;
            if (_defaultZoom > 400) _defaultZoom = 400;
            ReportViewer.ZoomMode = ZoomMode.Percent;
            ReportViewer.ZoomPercent = _defaultZoom;
        }

        private void BtnZoomOut_OnClick(object sender, RoutedEventArgs e)
        {
            _defaultZoom -= 25;
            if (_defaultZoom < 25) _defaultZoom = 25;
            ReportViewer.ZoomMode = ZoomMode.Percent;
            ReportViewer.ZoomPercent = _defaultZoom;
        }

        private delegate void ExportTo(object sender);

        private void ExportToFile(object sender)
        {
            try
            {
                var x = ReportViewer.LocalReport.ListRenderingExtensions();
                RenderingExtension render = null;

                var obj = (sender as string);

                switch (obj)
                {
                    case "Word":
                        render = x[5];
                        break;
                    case "Excel":
                        render = x[1];
                        break;
                    case "Pdf":
                        render = x[3];
                        break;
                }
                if (render != null)
                {
                    var DialogResult = ReportViewer.ExportDialog(render);
                    if (DialogResult == DialogResult.OK)
                    {
                        //MessageBox.Show("Done!");
                    }
                }
            }
            catch (Exception x)
            {
                //MessageBox.Show(x.Message);
            }
        }
        #endregion
    }
}
